<template>
    <div>
        <slot></slot>
    </div>
</template>

<script>
export default {
    name: 'AForm',
    props: {
        color: {
            type: String,
            default: null,
        },
        disabled: {
            type: Boolean,
            default: null,
        },
        size: {
            type: String,
            default: null,
        },
        sharp: {
            type: Boolean,
            default: null,
        },
        /**
         * 自动对齐label，不需要手动指定labelWidth
         */
        autoAlignLabel: {
            type: Boolean,
            default: true
        },
        /**
         * autoAlignLabel为false时生效
         */
        labelWidth: {
            type: Number,
        },
        labelAlign: {
            type: String,
            default: 'left'
        },
        labelPlain: {
            type: Boolean,
            default: false
        },
    },
    data() {
        return {
            validateFuncMap: new Map(),
            labelWidthMap: new Map(),
        }
    },
    computed: {
        myLabelWidth() {
            if (this.autoAlignLabel) {
                return Array.from(this.labelWidthMap.values()).sort((a, b) => b - a)[0]
            }
            return this.labelWidth
        }
    },
    methods: {
        addValidateFunc(key, func) {
            this.validateFuncMap.set(key, func)
        },
        removeValidateFunc(key) {
            this.validateFuncMap.delete(key)
        },
        addLabelWidth(key, width) {
            this.labelWidthMap.set(key, width)
        },
        removeLabelWidth(key) {
            this.labelWidthMap.delete(key)
        },
        async isValid() {
            let ps = Array.from(this.validateFuncMap.values()).map(validateFunc => {
                return new Promise(async resolve => {
                    let valid = await validateFunc()
                    resolve(valid)
                })
            })
            let results = await Promise.all(ps)
            return results.every(a => a)
        }
    },
    provide() {
        return {
            form: this
        }
    },
}
</script>